package com.imooc.SmartChargeStation.demo.netty.util;

import com.imooc.SmartChargeStation.demo.netty.handlers.ImoocClientProtobufHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ConnectUtil {
/*
    该类是一个Netty客户端连接工具类：
    1.建立Netty客户端连接
    2.自动重连机制

    为什么是这样？
    将NettyClient（客户端）理解成商店：商店开门后（启动监听）就固定在那里，等待顾客（客户端）上门（发起连接），不需要主动去找顾客。
    将NettyServe（服务端）理解成顾客：需要主动去商店（发起连接），如果商店临时关门（服务端下线），顾客会过一会儿再去（重连），直到商店重新开门。
 */
    private NioEventLoopGroup eventLoop;

    private Channel channel;

    public void connect(String host,int port) {

        eventLoop = new NioEventLoopGroup();

        Bootstrap bootstra = new Bootstrap();
        bootstra
                .group(eventLoop)
                .channel(NioSocketChannel.class)

                .handler(new ChannelInitializer<>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {

                        ChannelPipeline pipeline = channel.pipeline();

                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                        pipeline
                                .addLast(new ProtobufVarint32LengthFieldPrepender())
                                .addLast(new ProtobufEncoder())
                                .addLast(new ImoocClientProtobufHandler())
                        ;
                    }
                });

        doConnect(bootstra,host,port);
    }

    public void doConnect(Bootstrap bootstra,String host,int port) {

        log.info(">>>>>Netty 客户端启动中...");

        ChannelFuture future = null;
        try {
            future = bootstra.connect(host,port).sync();
            log.info(">>>>>Netty客户端开始监听: {}:{}<<<<<", host,port);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()) {
                        log.info(">>>>>Netty 客户端连接成功");
                    }else {
                        log.info(">>>>>Netty 客户端和服务端断开了连接, 重连中...");
                        final EventLoop loop = channelFuture.channel().eventLoop();
                        loop.schedule(new Runnable() {
                            @Override
                            public void run() {
                                doConnect(bootstra,host,port);
                            }
                        },10, TimeUnit.SECONDS);

                    }
                }
            });

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {

            log.info(">>>>>Netty客户端关闭....");

            if(eventLoop != null) {
                eventLoop.shutdownGracefully();
            }
            if(channel != null) {
                channel.closeFuture();
            }

        }
    }
}
